package com.bingoogolapple.qrcode.zxing;

import com.bingoogolapple.qrcode.core.CanvasUtil;
import com.bingoogolapple.qrcode.core.LogUtil;
import com.bingoogolapple.qrcode.core.TextUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Rect;

import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

import static ohos.agp.utils.TextAlignment.CENTER;

/**
 * 作者:王浩 邮件:bingoogolapple@gmail.com
 * 创建时间:16/4/8 下午11:22
 * 描述:创建二维码图片
 */
public class QRCodeEncoder {
    public static final Map<EncodeHintType, Object> HINTS = new EnumMap<>(EncodeHintType.class);

    static {
        HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8");
        HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        HINTS.put(EncodeHintType.MARGIN, 0);
    }

    private QRCodeEncoder() {
    }

    /**
     * 同步创建黑色前景色、白色背景色的二维码图片。该方法是耗时操作，请在子线程中调用。
     *
     * @param content 要生成的二维码图片内容
     * @param size    图片宽高，单位为px
     * @return PixelMap 返回二维码图片
     */
    public static PixelMap syncEncodeQRCode(String content, int size) {
        return syncEncodeQRCode(content, size, Color.BLACK.getValue(), Color.WHITE.getValue(), null);
    }

    /**
     * 同步创建指定前景色、白色背景色的二维码图片。该方法是耗时操作，请在子线程中调用。
     *
     * @param content         要生成的二维码图片内容
     * @param size            图片宽高，单位为px
     * @param foregroundColor 二维码图片的前景色
     * @return PixelMap 二维码图片
     */
    public static PixelMap syncEncodeQRCode(String content, int size, int foregroundColor) {
        return syncEncodeQRCode(content, size, foregroundColor, Color.WHITE.getValue(), null);
    }

    /**
     * 同步创建指定前景色、白色背景色、带logo的二维码图片。该方法是耗时操作，请在子线程中调用。
     *
     * @param content         要生成的二维码图片内容
     * @param size            图片宽高，单位为px
     * @param foregroundColor 二维码图片的前景色
     * @param logo            二维码图片的logo
     * @return PixelMap 二维码图片
     */
    public static PixelMap syncEncodeQRCode(String content, int size, int foregroundColor, PixelMap logo) {
        return syncEncodeQRCode(content, size, foregroundColor, Color.WHITE.getValue(), logo);
    }

    /**
     * 同步创建指定前景色、指定背景色、带logo的二维码图片。该方法是耗时操作，请在子线程中调用。
     *
     * @param content         要生成的二维码图片内容
     * @param size            图片宽高，单位为px
     * @param foregroundColor 二维码图片的前景色
     * @param backgroundColor 二维码图片的背景色
     * @param logo            二维码图片的logo
     * @return PixelMap 二维码图片
     */
    public static PixelMap syncEncodeQRCode(String content, int size, int foregroundColor, int backgroundColor, PixelMap logo) {
        PixelMap pixelMap = null;
        try {
            BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, HINTS);
            int[] pixels = new int[size * size];
            for (int y = 0; y < size; y++) {
                for (int x = 0; x < size; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * size + x] = foregroundColor;
                    } else {
                        pixels[y * size + x] = backgroundColor;
                    }
                }
            }
            pixelMap = CanvasUtil.createPixelMap(size,size);
            pixelMap.writePixels(pixels, 0, size, new Rect(0, 0, size, size));
            return addLogoToQRCode(pixelMap,logo);
        } catch (Exception e) {
            LogUtil.error("err: " + e.getMessage());
            return null;
        }
    }

    /**
     * 添加带logo的二维码图片
     *
     * @param src         要生成的二维码图片资源
     * @param logo            二维码图片的logo
     * @return PixelMap 二维码图片
     */
    public static PixelMap addLogoToQRCode(PixelMap src, PixelMap logo) {
        if (src == null || logo == null) {
            return src;
        }

        int srcWidth = src.getImageInfo().size.width;
        int srcHeight = src.getImageInfo().size.height;
        int logoWidth = logo.getImageInfo().size.width;
        int logoHeight = logo.getImageInfo().size.height;

        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        PixelMap bitmap = CanvasUtil.createPixelMap(srcWidth, srcHeight);
        try {
            Canvas canvas = new Canvas(new Texture(bitmap));
            canvas.drawPixelMapHolder(new PixelMapHolder(src), 0, 0, new Paint());
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawPixelMapHolder(new PixelMapHolder(logo), (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, new Paint());
            canvas.save();
            canvas.restore();
        } catch (Exception e) {
            LogUtil.error(e.getMessage());
            bitmap = null;
        }
        return bitmap;
    }


    /**
     * 同步创建条形码图片
     *
     * @param content  要生成条形码包含的内容
     * @param width    条形码的宽度，单位px
     * @param height   条形码的高度，单位px
     * @param textSize 字体大小，单位px，如果等于0则不在底部绘制文字
     * @return 返回生成条形的位图
     */
    public static PixelMap syncEncodeBarcode(String content, int width, int height, int textSize) {
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 0);

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, width, height, hints);
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            PixelMap bitmap = CanvasUtil.createPixelMap(width,height);
            bitmap.writePixels(pixels,0,width,new Rect(0,0,width,height));
            if (textSize > 0) {
                bitmap = showContent(bitmap, content, textSize);
            }
            return bitmap;
        } catch (Exception e) {
            LogUtil.error(e.getMessage());
        }

        return null;
    }

    /**
     * 显示条形的内容
     *
     * @param barcodeBitmap 已生成的条形码的位图
     * @param content       条形码包含的内容
     * @param textSize      字体大小，单位px
     * @return 返回生成的新条形码位图
     */
    public static PixelMap showContent(PixelMap barcodeBitmap, String content, int textSize) {
        if (TextUtils.isEmpty(content) || null == barcodeBitmap) {
            return null;
        }
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL_STYLE);
        paint.setTextSize(textSize);
        paint.setTextAlign(CENTER);
        int textWidth = (int) paint.measureText(content);
        Paint.FontMetrics fm = paint.getFontMetrics();
        int textHeight = (int) (fm.bottom - fm.top);
        int baseLine = barcodeBitmap.getImageInfo().size.height + textHeight;

        PixelMap pixelMap = CanvasUtil.createPixelMap(barcodeBitmap.getImageInfo().size.width,barcodeBitmap.getImageInfo().size.height + 2*textHeight);
        Canvas canvas = new Canvas(new Texture(pixelMap));
        canvas.drawPixelMapHolder(new PixelMapHolder(barcodeBitmap),0,0,new Paint());
        canvas.drawText(new Paint(),content , barcodeBitmap.getImageInfo().size.width / 2, baseLine);
        canvas.save();
        canvas.restore();
        return pixelMap;
    }

}
